package com.xtt.util.retry;

import java.io.IOException;
import java.lang.reflect.Modifier;
import java.util.List;

import com.xtt.util.spring.ClassUtils;

public class RetryUtils {
   /**
    * 重试某方法
    * @param counter
    * @param clazz
    * @param methodName
    * @param args
    * @param paramTypes
    * @return
    * @throws Exception
    */
   @SuppressWarnings("unchecked")
public static <T>T retry(Integer counter,Class<?> clazz,String methodName,List<Object> args,List<Class<?>> paramTypes) throws Exception {
	   if(counter < 1) {
		   throw new Exception("重复次数超过限制");
	   }
	   try {
		   java.lang.reflect.Method method;
		   if(paramTypes == null || paramTypes.size() == 0) {
			   method = clazz.getMethod(methodName);
			   if(Modifier.isStatic(method.getModifiers())) {//静态方法
				   return (T)method.invoke(null);
			   } else {
				   Object obj = clazz.newInstance();
				   return (T)method.invoke(obj);
			   }
		   } else {
			   Class<?>[] clazzs = new Class[paramTypes.size()];
			   method = clazz.getMethod(methodName, paramTypes.toArray(clazzs));
			   if(Modifier.isStatic(method.getModifiers())) {//非静态方法
				   return (T)method.invoke(null,args);
			   } else {
				   Object obj = clazz.newInstance();
				   return (T)method.invoke(obj, args);
			   }
		   }
	   } catch (Exception e) {
           if(e instanceof IOException || e.getCause() instanceof IOException) {
               System.out.println("重试,还剩重复次数："+(counter-1));
               return retry(counter-1, clazz, methodName, args,paramTypes);
           } else {
               throw e;
           }
	   }
   }
   
   /**
    * 
    * @param counter
    * @param clazz
    * @param method
    * @return
    * @throws Exception
    */
   public static <T>T retry(Integer counter,Class<?> clazz,Method method) throws Exception {
	   return retry(counter, clazz, method.getMethodName(), method.getArgs(), method.getParamTypes());
   }
   
   @SuppressWarnings("unchecked")
   public static <T>T retry(Integer counter,Object instance,String methodName,List<Object> args,List<Class<?>> paramTypes) throws Exception {
	   if(counter < 1) {
		   throw new Exception("重复次数超过限制");
	   }
	   try {
		   java.lang.reflect.Method method;
		   if(paramTypes == null || paramTypes.size() == 0) {
			   method = instance.getClass().getMethod(methodName);
			   return (T)method.invoke(instance);
		   } else {
			   Class<?>[] clazzs = new Class[paramTypes.size()];
			   method = instance.getClass().getMethod(methodName, paramTypes.toArray(clazzs));
			   return (T)method.invoke(instance, args);
		   }
	   } catch (Exception e) {
           if(e instanceof IOException || e.getCause() instanceof IOException) {
               System.out.println("重试,还剩重复次数："+(counter-1));
               return retry(counter-1, instance, methodName, args,paramTypes);
           } else {
               throw e;
           }
	   }
   }
}
